﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using HandyControl.Tools.Extension;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
using System.Xml.Linq;
using WindowsCountdownShutdownSoftware.ViewModels.Dialogs;
using WindowsCountdownShutdownSoftware.Views.Dialogs;

namespace WindowsCountdownShutdownSoftware.ViewModels
{
    public partial class MainViewModel : ObservableObject
    {
        /// <summary>
        /// 根据选择方式设置关机方式
        /// </summary>
        [ObservableProperty]
        public List<string> _selectMethod = new List<string>() { "根据关机时间", "根据倒计时"};

        /// <summary>
        /// 选择方式设置关机方式的下标
        /// </summary>
        [ObservableProperty]
        public int _selectMethodIndex = 0;


        /// <summary>
        /// 关机时间
        /// </summary>
        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SetShutdownTimeCommand))]
        public DateTime _shutdownDateTime = DateTime.Now;
        
        /// <summary>
        /// 选择时间单位
        /// </summary>
        [ObservableProperty]
        public List<string> _dateTimeSelector = new List<string>() { "秒", "分钟", "小时", "天", "月", "年" };


        /// <summary>
        /// 选择时间单位的下标
        /// </summary>
        [ObservableProperty]
        public int _dateTimeSelectorIndex = 0;

        /// <summary>
        /// 倒计时数值
        /// </summary>
        [ObservableProperty]
        public int _countdownValue = 1;


        /// <summary>
        /// 对话框确认信息
        /// </summary>
        [ObservableProperty]
        public string _shutdownConfirmedInfo = "";


        /// <summary>
        /// 是否确定关机操作【按钮提示】
        /// </summary>
        [ObservableProperty]
        public bool _isUploading = false;

        /// <summary>
        /// 关机按钮显示文本
        /// </summary>
        [ObservableProperty]
        public string _confirmShutdownTimeBtn = "确定关机时间";


        /// <summary>
        /// 启动关机指令时间
        /// </summary>
        [ObservableProperty]
        public string _shutdownStarted;


        /// <summary>
        /// 关机间隔时间
        /// </summary>
        [ObservableProperty]
        public string _shutdownInterval;


        /// <summary>
        /// 执行关机指令时间
        /// </summary>
        [ObservableProperty]
        public string _shutdownCommandExecuted;


        /// <summary>
        /// 滚动条数值
        /// </summary>
        [ObservableProperty]
        public long _scrollbarValue = 0;

        /// <summary>
        /// 最大滚动条数值
        /// </summary>
        [ObservableProperty]
        public long _maxScrollbarValue = 0;

        /// <summary>
        /// 关机定时器
        /// </summary>
        private DispatcherTimer _scheduledTimer;

        /// <summary>
        /// 滚动条定时器
        /// </summary>
        private DispatcherTimer _showTimer;


        /// <summary>
        /// 当前时间
        /// </summary>
        private DateTime currentDateTime;

        private bool CanSetShutdownTime() => SelectMethodIndex == 0 ? ShutdownDateTime != null : CountdownValue != 0;




        /// <summary>
        /// 设置关闭时间
        /// </summary>
        [RelayCommand(CanExecute = nameof(CanSetShutdownTime))]
        private async void SetShutdownTime()
        {

            if (!IsUploading)
            {
                //ShutdownConfirmedInfo = "您确定要中止关机程序吗?";
                //var response = await Dialog.Show<TextDialog>().Initialize<TextDialogViewModel>(vm => vm.TextInfo = ShutdownConfirmedInfo).GetResultAsync<int>();

                //if (response == 1)
                //{

                    
                //}

                IsUploading = false;
                ScrollbarValue = 0;
                ConfirmShutdownTimeBtn = "确定关机时间";

                ShutdownStarted = "";
                ShutdownInterval = "";
                ShutdownCommandExecuted = "";

                _showTimer.Stop();
                _showTimer = null;

                // 停止关机计时器
                _scheduledTimer.Stop();

                // 取消关机
                System.Diagnostics.Process.Start("shutdown", "/a");

                return;

            }

            // 当前时间
            currentDateTime = DateTime.Now;

            if (SelectMethodIndex == 0)
            {
                var ShutdownDateTimeString = ShutdownDateTime > currentDateTime ? ShutdownDateTime.ToString("yyyy-MM-dd HH:mm:ss") : "立即";

                ShutdownConfirmedInfo = $"您确定要在{ShutdownDateTimeString}关机吗?";
            } else
            {
                ShutdownConfirmedInfo = $"您确定要在{CountdownValue}{DateTimeSelector[DateTimeSelectorIndex]}之后关机吗?";
            }

            var res = await Dialog.Show<TextDialog>().Initialize<TextDialogViewModel>(vm => vm.TextInfo = ShutdownConfirmedInfo).GetResultAsync<int>();

            // 取消关机操作
            if (res == 0)
            {
                Growl.Error("取消关机操作！");
                IsUploading = false;

                await Task.Delay(1000);
                Growl.Clear();

                return;
            }

            IsUploading = true;
            ConfirmShutdownTimeBtn = "中止关机程序";


            // 执行关机操作
            if (SelectMethodIndex == 0)
            {
                if (ShutdownDateTime < currentDateTime)
                {
                    ShutdownDateTime = currentDateTime;
                }
                
                ShutdownStarted = currentDateTime.ToString("yyyy-MM-dd HH:mm:ss");
                ShutdownInterval = ShutdownDateTime > currentDateTime ? GetIntervalTime(ShutdownDateTime, DateTime.Now) : "立即关机";
                ShutdownCommandExecuted = ShutdownDateTime >= currentDateTime ? ShutdownDateTime.ToString("yyyy-MM-dd HH:mm:ss") : currentDateTime.ToString("yyyy-MM-dd HH:mm:ss");
                MaxScrollbarValue = GetIntervalTimeByLong(currentDateTime, ShutdownDateTime);
            }
            else
            {
                ShutdownStarted = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                ShutdownInterval = GetIntervalTimeFromMilliseconds(GetMillisecondsBy(CountdownValue, DateTimeSelectorIndex));
                ShutdownCommandExecuted = DateTime.Now.AddMilliseconds(GetMillisecondsBy(CountdownValue, DateTimeSelectorIndex)).ToString("yyyy-MM-dd HH:mm:ss");
                MaxScrollbarValue = GetMillisecondsBy(CountdownValue, DateTimeSelectorIndex);
            }

            // 创建关机定时器
            _scheduledTimer = new DispatcherTimer();

            if (SelectMethodIndex == 0)
            {
                _scheduledTimer.Interval = ShutdownDateTime > currentDateTime ? ShutdownDateTime - currentDateTime : new TimeSpan(0);
            } else
            {
                _scheduledTimer.Interval = DateTime.Now.AddMilliseconds(GetMillisecondsBy(CountdownValue, DateTimeSelectorIndex)) - DateTime.Now;
            }
                
            _scheduledTimer.Tick += OnScheduledTimeReached;
            _scheduledTimer.Start();

            // 创建滚动条定时器
            
            _showTimer = new DispatcherTimer();

            _showTimer.Interval = TimeSpan.FromSeconds(1);

            _showTimer.Tick += OnShowTimeReached;
            _showTimer.Start();


        }


        /// <summary>
        /// 关机定时执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnScheduledTimeReached(object? sender, EventArgs e)
        {
            _scheduledTimer.Stop();
            _scheduledTimer = null;

            // 执行你的“事件”
            Growl.Error("关机");

            // 立即关机
            // 模拟一些工作
            System.Threading.Thread.Sleep(1000);

            // ✅ 关键步骤：启动一个独立的关机进程
            try
            {
                // 强制关机
                // 方法1：使用 Process.Start 直接调用 shutdown.exe
                Process.Start(new ProcessStartInfo
                {
                    FileName = "shutdown",
                    Arguments = "/s /f /t 5", // /s 表示关机，/t 5 表示5秒后关机
                    UseShellExecute = false, // 可选，但推荐显式设置
                    CreateNoWindow = true   // 不显示命令窗口
                });

                Console.WriteLine("已发出关机指令，程序即将退出。");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"启动关机失败: {ex.Message}");
                return;
            }


            // ✅ 主程序退出，但关机任务已在后台运行
            Environment.Exit(0); // 或直接让 Main 方法结束
        }

        /// <summary>
        /// 滚动条定时执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnShowTimeReached(object? sender, EventArgs e)
        {
            ScrollbarValue += 1000;

        }


        private long GetIntervalTimeByLong(DateTime startTime, DateTime endTime)
        {
            TimeSpan interval = endTime - startTime;
            return (long)interval.TotalMilliseconds;
        }

        /// <summary>
        /// 窗口关闭
        /// </summary>
        [RelayCommand]
        private async void CloseSoftWare()
        {
            ShutdownConfirmedInfo = "您确定要关闭当前程序吗?";

            var res = await Dialog.Show<TextDialog>().Initialize<TextDialogViewModel>(vm =>
            {
                vm.TextInfo = ShutdownConfirmedInfo;
            }).GetResultAsync<int>();

            // 关闭当前程序
            if (res == 1)
            {
                Environment.Exit(0);
            }
            
        }

        /// <summary>
        /// 获取间隔时间
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        private string GetIntervalTime(DateTime startTime, DateTime endTime)
        {
            if (endTime < startTime)
                return GetIntervalTime(endTime, startTime); // 可交换确保正向

            int years = 0, months = 0, days = 0;
            DateTime tempStart = startTime;

            // 计算完整月数（按年月递增）
            while (tempStart.AddMonths(1) <= endTime)
            {
                tempStart = tempStart.AddMonths(1);
                months++;
            }

            years = months / 12;
            months = months % 12;

            // 剩下的天数
            TimeSpan remaining = endTime - tempStart;
            days = remaining.Days;
            int hours = remaining.Hours;
            int minutes = remaining.Minutes;
            int seconds = remaining.Seconds;

            var parts = new List<string>();

            if (years > 0) parts.Add($"{years}年");
            if (months > 0) parts.Add($"{months}个月");
            if (days > 0) parts.Add($"{days}天");
            if (hours > 0) parts.Add($"{hours}小时");
            if (minutes > 0) parts.Add($"{minutes}分钟");
            if (seconds > 0) parts.Add($"{seconds}秒");

            return string.Join("", parts);
        }

        /// <summary>
        /// 根据倒计时算出毫秒值
        /// </summary>
        /// <param name="value"></param>
        /// <param name="unit"></param>
        /// <returns></returns>
        private long GetMillisecondsBy(int value , int unit)
        {
            long milliseconds = 0;
            switch (unit) {
                case 0:
                    milliseconds = value * 1000;
                    break;
                case 1:
                    milliseconds = value * 60000;
                    break;
                case 2:
                    milliseconds = value * 3600000;
                    break;
                case 3:
                    milliseconds = value * 86400000;
                    break;
                case 4:
                    milliseconds = value * 30L * 86400000;
                    break;
                case 5:
                    milliseconds = value * 365L * 86400000;
                    break;
            }

            return milliseconds;
        }


        /// <summary>
        /// 根据毫秒值计算年月日时分秒
        /// </summary>
        /// <param name="milliseconds"></param>
        /// <returns></returns>
        private string GetIntervalTimeFromMilliseconds(long milliseconds)
        {
            // 将毫秒转换为 TimeSpan
            var ts = TimeSpan.FromMilliseconds(Math.Abs(milliseconds));

            long totalSeconds = (long)ts.TotalSeconds;

            const long SecondsPerMinute = 60;
            const long SecondsPerHour = 60 * 60;
            const long SecondsPerDay = 24 * 60 * 60;
            const long SecondsPerMonth = 30 * SecondsPerDay; // 近似
            const long SecondsPerYear = 365 * SecondsPerDay; // 近似

            var parts = new List<string>();

            long years = totalSeconds / SecondsPerYear;
            if (years > 0)
            {
                parts.Add($"{years}年");
                totalSeconds -= years * SecondsPerYear;
            }

            long months = totalSeconds / SecondsPerMonth;
            if (months > 0)
            {
                parts.Add($"{months}个月");
                totalSeconds -= months * SecondsPerMonth;
            }

            long days = totalSeconds / SecondsPerDay;
            if (days > 0)
            {
                parts.Add($"{days}天");
                totalSeconds -= days * SecondsPerDay;
            }

            long hours = totalSeconds / SecondsPerHour;
            if (hours > 0)
            {
                parts.Add($"{hours}小时");
                totalSeconds -= hours * SecondsPerHour;
            }

            long minutes = totalSeconds / SecondsPerMinute;
            if (minutes > 0)
            {
                parts.Add($"{minutes}分钟");
                totalSeconds -= minutes * SecondsPerMinute;
            }

            long seconds = totalSeconds;
            if (seconds > 0)
            {
                parts.Add($"{seconds}秒");
            }

            return parts.Count > 0 ? string.Join("", parts) : "0秒";
        }
    }
}
